//封装axios,请求处理
import axios from "axios";
import { ElMessage } from "element-plus";

import router from "@/router/index.js";

//import { getToken } from './token/index.js';
const token = ""

//创建axios
const request = axios.create({
    baseURL: 'http://localhost:8888',
    withCredentials: false, //用于配置请求接口跨域时是否需要凭证
    timeout: 30000
})

//配置请求头的参数类型
axios.defaults.headers['Content-Type'] = 'application/json?chatset=utf-8'

//配置请求的拦截器
request.interceptors.request.use((config)=>{
    //在请求头添加token，判断是否需要发送token
    //token应从pinia中获取
    if(token){
        config.headers['Magic-Authorization'] = token;
    }
    return config;
    },(Error)=>{
        console.log("请求异常----",Error);
        return Promise.reject(Error);
    
})


//配置响应拦截器
request.interceptors.response.use((response)=>{
    let {msg,code} = response.data
    console.log("code----",code,'msg---',msg);
    if(code == null){
        return response;
    }else if(code == 200){
        return response;
    }else if(code == 500){
        ElMessage.error('服务端异常！');
    }else if(code == 401){
        ElMessage.error('没有操作权限！');
    }else if(code == 403){
        ElMessage.error('登录过期！');
        window.sessionStorage.clear;
        router.push('/login');
    }
    return Promise.reject(msg);
},(error)=>{
    ElMessage.error('erro----------',error);
    window.sessionStorage.clear();
    router.push('/login');
    return Promise.reject(msg);
})

export default request;